package riofrio.examples;

import java.util.IdentityHashMap;
import riofrio.TreeNode;
import static riofrio.TreeNode.with;
import riofrio.DepthFirstWalk;

/**
 *
 * @author Victor Hugo Herrera Maldonado
 */
public class Calculator {

    public static void main(String[] args) {
        TreeNode<String> root=
            with("*")
                .children(
                        with("+").childrenWith("5", "4"),
                        with("-").childrenWith("3", "6")
                );
        
        double value=new DepthFirstWalk<>(root, DepthFirstWalk.Order.POST_ORDER).eval((node, results) -> {
            if (node.isParent()) {
                double result = 0;
                switch (node.getContent()) {
                    case "+":
                        result = 0;
                        for(TreeNode<String> child:node) {
                            result += results.get(child);
                        }
                        break;
                    case "-":
                        result = 0;
                        for(TreeNode<String> child:node) {
                            result -= results.get(child);
                        }
                        break;
                    case "*":
                        result = 1;
                        for(TreeNode<String> child:node) {
                            result *= results.get(child);
                        }
                        break;
                    default:
                        throw new AssertionError();
                }
                return result;
            } else {
                return Double.parseDouble(node.getContent());
            }
        });
        System.out.printf("Result: %s%n", value);
    }

}
